//
//  InfoVC.m
//  AddressBook
//
//  Created by dllo on 15/11/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "InfoVC.h"
#import "CoreData.h"
#import "LTView.h"
#import <Masonry.h>
#import "Person.h"
#import "ViewController.h"
#import "MapViewController.h"


@interface InfoVC ()<UITextFieldDelegate, MapViewControllerDelegate>

@property(nonatomic, strong) CoreData *manager;
@property(nonatomic, copy) NSString *changeStr;

@end

@implementation InfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    //
    self.manager = [CoreData defaults];
    
    //
    [self createView];
    
    //
    [self createData];
    
    // delete
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(barButton:)];
    
    // map
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.backgroundColor = [UIColor greenColor];
    [button setTitle:@"Map" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(-100);
        make.centerX.equalTo(self.view.mas_centerX).with.offset(0);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width / 4);
    }];

    
}

#pragma mark - MapViewDelegate
- (void)takeValue:(NSString *)location {
    LTView *birthTextField = (LTView *)[self.view viewWithTag:2005];
    birthTextField.textField.text = location;
    [self textFieldDidEndEditing:birthTextField.textField];
}



#pragma mark - map
- (void)button:(UIButton *)button {
    MapViewController *mapVC = [[MapViewController alloc] init];
    mapVC.delegate = self;
    LTView *birthTextField = (LTView *)[self.view viewWithTag:2005];
    mapVC.location = birthTextField.textField.text;
    [self.navigationController pushViewController:mapVC animated:YES];
}



#pragma mark - createView
- (void)createView {
    // name
    LTView *nameTextField = [[LTView alloc] init];
    [self.view addSubview:nameTextField];
    nameTextField.tag = 2000;
    nameTextField.textField.delegate = self;
    nameTextField.label.text = @"姓名";
    
    [nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(84);
        make.centerX.equalTo(self.view.mas_centerX).with.offset(0);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width / 2);
    }];
    
    // telephone
    LTView *telephoneTextField = [[LTView alloc] init];
    [self.view addSubview:telephoneTextField];
    telephoneTextField.tag = 2001;
    telephoneTextField.textField.delegate = self;
    telephoneTextField.label.text = @"电话";
    
    [telephoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameTextField.mas_bottom).with.offset(20);
        make.centerX.equalTo(self.view.mas_centerX).with.offset(0);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width / 2);
    }];
    
    // sex
    LTView *sexTextField = [[LTView alloc] init];
    [self.view addSubview:sexTextField];
    sexTextField.tag = 2002;
    sexTextField.textField.delegate = self;
    sexTextField.label.text = @"性别";
    
    [sexTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(telephoneTextField.mas_bottom).with.offset(20);
        make.centerX.equalTo(self.view.mas_centerX).with.offset(0);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width / 2);
    }];
    
    // number
    LTView *numberTextField = [[LTView alloc] init];
    [self.view addSubview:numberTextField];
    numberTextField.tag = 2003;
    numberTextField.textField.delegate = self;
    numberTextField.label.text = @"学号";
    
    [numberTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(sexTextField.mas_bottom).with.offset(20);
        make.centerX.equalTo(self.view.mas_centerX).with.offset(0);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width / 2);
    }];
    
    // QQ
    LTView *QQTextField = [[LTView alloc] init];
    [self.view addSubview:QQTextField];
    QQTextField.tag = 2004;
    QQTextField.textField.delegate = self;
    QQTextField.label.text = @"QQ";
    
    [QQTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(numberTextField.mas_bottom).with.offset(20);
        make.centerX.equalTo(self.view.mas_centerX).with.offset(0);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width / 2);
    }];
    
    // jiguan
    LTView *birthTextField = [[LTView alloc] init];
    [self.view addSubview:birthTextField];
    birthTextField.tag = 2005;
    birthTextField.textField.delegate = self;
    [birthTextField.textField addTarget:self action:@selector(birthTextFieldUp:) forControlEvents:UIControlEventEditingDidBegin];
    [birthTextField.textField addTarget:self action:@selector(birthTextFieldDown:) forControlEvents:UIControlEventEditingDidEnd];
    birthTextField.label.text = @"籍贯";
    
    [birthTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(QQTextField.mas_bottom).with.offset(20);
        make.centerX.equalTo(self.view.mas_centerX).with.offset(0);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width / 2);
    }];

}



#pragma mark - createData
- (void)createData {
    // 查询CoreData
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], self.nameStr];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
    // 赋值
    LTView *nameTextField = (LTView *)[self.view viewWithTag:2000];
    LTView *telephoneTextField = (LTView *)[self.view viewWithTag:2001];
    LTView *sexTextField = (LTView *)[self.view viewWithTag:2002];
    LTView *numberTextField = (LTView *)[self.view viewWithTag:2003];
    LTView *QQTextField = (LTView *)[self.view viewWithTag:2004];
    LTView *birthTextField = (LTView *)[self.view viewWithTag:2005];
    
    Person *per = fetchedObjects[0];
    
    nameTextField.textField.text = per.name;
    telephoneTextField.textField.text = per.telephone;
    sexTextField.textField.text = per.sex;
    numberTextField.textField.text = per.number;
    QQTextField.textField.text = per.qq;
    birthTextField.textField.text = per.birth;
}



#pragma mark - changeValue
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.changeStr = textField.text;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    LTView *nameTextField = (LTView *)[self.view viewWithTag:2000];
    LTView *telephoneTextField = (LTView *)[self.view viewWithTag:2001];
    LTView *sexTextField = (LTView *)[self.view viewWithTag:2002];
    LTView *numberTextField = (LTView *)[self.view viewWithTag:2003];
    LTView *QQTextField = (LTView *)[self.view viewWithTag:2004];
    LTView *birthTextField = (LTView *)[self.view viewWithTag:2005];
    
    NSString *str;
    NSString *takeValue;
    if (textField == nameTextField.textField) {
        str = @"name";
        takeValue = nameTextField.textField.text;
    } else if (textField == telephoneTextField.textField) {
        str = @"telephone";
        takeValue = telephoneTextField.textField.text;
    } else if (textField == sexTextField.textField) {
        str = @"sex";
        takeValue = sexTextField.textField.text;
    } else if (textField == numberTextField.textField) {
        str = @"number";
        takeValue = numberTextField.textField.text;
    } else if (textField == QQTextField.textField) {
        str = @"qq";
        takeValue = QQTextField.textField.text;
    } else if (textField == birthTextField.textField) {
        str = @"birth";
        takeValue = birthTextField.textField.text;
    }
    
    [self changeValue:str takeValue:takeValue];
    
}

- (void)changeValue:(NSString *)str takeValue:(NSString *)takeValue {
    // 修改
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", str, @"%@"], self.changeStr];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:str
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    NSLog(@"%@", fetchedObjects);
    
    [self xiugai:fetchedObjects Attribute:str takeValue:takeValue];
    
}

- (void)xiugai:(NSArray *)arr Attribute:(NSString *)str takeValue:(NSString *)takeValue {
    Person *per = arr.lastObject;
    if ([str isEqualToString:@"name"]) {
        per.name = takeValue;
    } else if ([str isEqualToString:@"telephone"]) {
        per.telephone = takeValue;
    } else if ([str isEqualToString:@"sex"]) {
        per.sex = takeValue;
    } else if ([str isEqualToString:@"number"]) {
        per.number = takeValue;
    } else if ([str isEqualToString:@"birth"]) {
        per.birth = takeValue;
    } else if ([str isEqualToString:@"qq"]) {
        per.qq = takeValue;
    }
    
    [self.manager saveContext];
}



#pragma mark - delete
- (void)barButton:(UIBarButtonItem *)button {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否删除此联系人" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    // 确定
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // 查找
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], self.nameStr];
        [fetchRequest setPredicate:predicate];
        // Specify how the fetched objects should be sorted
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                       ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        
        for (Person *per in fetchedObjects) {
            [self.manager.managedObjectContext deleteObject:per];
        }
        
        [self.manager saveContext];
        
        // 跳转
        [self.navigationController popViewControllerAnimated:YES];
        
    }];
    
    // 取消
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    
    [alert addAction:cancel];
    [alert addAction:alertAction];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}



#pragma mark - birthTextFieldAction
- (void)birthTextFieldUp:(UITextField *)textField {
    self.view.transform = CGAffineTransformTranslate(self.view.transform, 0, -50);
}

- (void)birthTextFieldDown:(UITextField *)textField {
    self.view.transform = CGAffineTransformTranslate(self.view.transform, 0, 50);
}



#pragma mark - touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    LTView *nameTextField = (LTView *)[self.view viewWithTag:2000];
    LTView *telephoneTextField = (LTView *)[self.view viewWithTag:2001];
    LTView *sexTextField = (LTView *)[self.view viewWithTag:2002];
    LTView *numberTextField = (LTView *)[self.view viewWithTag:2003];
    LTView *QQTextField = (LTView *)[self.view viewWithTag:2004];
    LTView *birthTextField = (LTView *)[self.view viewWithTag:2005];
    
    [nameTextField.textField resignFirstResponder];
    [telephoneTextField.textField resignFirstResponder];
    [sexTextField.textField resignFirstResponder];
    [numberTextField.textField resignFirstResponder];
    [QQTextField.textField resignFirstResponder];
    [birthTextField.textField resignFirstResponder];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
